package org.demo.nio.reactor.multiplereactor;

import org.demo.nio.reactor.multiplethread.RWHandler;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.spi.SelectorProvider;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by tangwy on 2017/10/31.
 */
public class Acceptor implements Runnable {
    private int i;
    private ServerSocketChannel ssc;
    private SelectorProvider selectorProvider;
    private SubReactor[] subReactors=new SubReactor[4];
    private ThreadPoolExecutor tpe=new ThreadPoolExecutor(4,4,1000, TimeUnit.SECONDS,new ArrayBlockingQueue<Runnable>(10));
    public Acceptor(ServerSocketChannel ssc,SelectorProvider selectorProvider) throws IOException {
        //判断是否为null
        this.selectorProvider = selectorProvider;
        this.ssc = ssc;
        for(int i=0;i<subReactors.length;i++){
            subReactors[i]=new SubReactor(selectorProvider);
            tpe.submit(subReactors[i]);
        }
    }

    @Override
    public void run() {
        try {
            SocketChannel channel = ssc.accept();
            if(channel!=null){
                System.out.println("accept");
                subReactors[i++].register(channel);
                if(i==subReactors.length){
                    i=0;
                }
                //tpe.submit();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
